package com.software.car.handler;

import com.software.car.common.utils.CusAccessObjectUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * 日志切面
 * 获取所有请求进行记录
 *
 * @Author 魔法はまだ解けない
 * @Date 2021/3/8
 */
@Aspect
@Component
public class HttpAspect {

    @Autowired
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpAspect.class);

    /**
     * @Pointcut 声明切入点表达式。
     * 扫描所有controller
     */
    @Pointcut("execution(public * com.software.car.controller.*.*(..))")
    public void log() {
        LOGGER.info("切入");
    }

    /**
     * @Before：前置通知，在方法执行前执行
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        //接口路径
        LOGGER.info("执行路径——requestURI:{}", request.getRequestURI());
        //method
        LOGGER.info("请求方式——method:{}", request.getMethod());
        //类方法
        LOGGER.info("执行方法——class_method:{}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        //获取用户真实Ip
        String ip = CusAccessObjectUtil.getIpAddress(request);
        LOGGER.info("用户ip:{}", ip);
    }
}
